package com.xxgc.demo.controller;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.xxgc.demo.controller.result.Result;
import com.xxgc.demo.entity.UserInfo;
import com.xxgc.demo.service.IUserInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Set;

/**
 * @Author: Sjy
 * @Date :2023/10/12 - 10 - 12 - 21:05
 * 多数据源测试
 */
@Slf4j
@Tag(name = "数据源")
@RestController
@RequestMapping("/data_source")
public class MoreDataSourceController {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private IUserInfoService iUserInfoService;

    @Operation(summary = "查看所有数据源",description = "查看当前项目有哪些数据源")
    @GetMapping("/getAllDataSource")
    public Result<Set<String>> getAllDataSource(){
        //把数据源对象转成德鲁伊数据源对象
        DynamicRoutingDataSource drDataSource = (DynamicRoutingDataSource) dataSource;
        Set<String> set = drDataSource.getDataSources().keySet();
        return Result.ok(set);
    }

    @Operation(summary = "查看当前数据源",description = "查看当前数据源")
    @GetMapping("/getAllDataSourceNow")
    public Result getAllDataSourceNow(){
        String peek = DynamicDataSourceContextHolder.peek();
        log.info(peek);
        return Result.ok(peek);
    }


    @Operation(summary = "添加用户",description = "添加用户")
    @PostMapping("/addUserInfo")
    public Result addUserInfo(@RequestBody UserInfo userInfo){
        iUserInfoService.save(userInfo);
        return Result.ok();
    }

    @Operation(summary = "模拟系统爆炸",description = "模拟系统爆炸")
    @PostMapping("/error")
    public Result error() throws SQLException {
        throw new SQLException();
    }


    @DS("logs")
    @Operation(summary = "制定当前接口操作某个库",description = "不影响项目其他接口")
    @PostMapping("/addUserInfoVip")
    public Result addUserInfoVip(@RequestBody UserInfo userInfo){
        //手动切数据源
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("logs");

        iUserInfoService.save(userInfo);
        return Result.ok();
    }

}
